//
//  TranslationListView.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/13.
//  Copyright © 2025 考拉🐨. All rights reserved.
//

import UIKit
import Reusable
import SnapKit

extension TranslationListView: NibLoadable {}

class TranslationListView: UIView {
    
    @IBOutlet weak var filterButton: UIButton!
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var submitButton: UIButton!
    
    private lazy var filterView: TranslationFilterView = {
        TranslationFilterView.loadFromNib()
    }()
    
    var didSelectedTranslationBlock: ((TranslatorsModel?) -> Void)?
    
    var list: [TranslatorsModel] = []
    var page: Int = 1
    
    var requestLang: String = ""
    var knowCityId: String = ""
    // 选择的地区名字
    var knowCityName: String = ""
    var professionalIds: String = ""
    // 价格选择
    var intentionScore: String = ""
    // 地区 id
    var country: String = ""
    
    var translationFilterUIModels: [TranslationFilterUIModel] = []
    
    override func awakeFromNib() {
        super.awakeFromNib()
        xLog("awakeFromNib")
        initUI()
        initRefresh()
        // loadData()
    }
    
    func initData() {
        loadData()
    }
    
    func reloadUI() {
        // 隐藏其他页面
        filterView.isHidden = true
        filterView.cityView.isHidden = true
        
        // 反显数据
        filterView.requestLang = requestLang
        filterView.knowCityId = knowCityId
        filterView.knowCityName = knowCityName
        filterView.professionalIds = professionalIds
        filterView.intentionScore = intentionScore
        filterView.country = country
    }
    
    // 更新语言
    @objc private func updateLanguageAction() {
    }
    
    @IBAction func filterAction(_ sender: Any) {
        if translationFilterUIModels.count > 0 {
            var uiModels: [TranslationFilterUIModel] = []
            translationFilterUIModels.forEach { uiModel in
                var subLis: [TranslationFilterModel] = []
                uiModel.list.forEach { model in
                    subLis.append(model.copy() as! TranslationFilterModel)
                }
                let ui = TranslationFilterUIModel(id: uiModel.id, title: uiModel.title, titleRu: uiModel.titleRu, list: subLis)
                uiModels.append(ui)
            }
            
            uiModels.forEach { uiModel in
                uiModel.list.forEach { model in
                    if model.isSelected {
                        xLog("\(uiModel.title) ====== \(model.name)")
                    }
                }
            }
            filterView.list = uiModels
        }
        filterView.isHidden = false
    }
    
    @IBAction func submitAction(_ sender: Any) {
        let model = list.filter({ $0.isSelected }).first
        didSelectedTranslationBlock?(model)
    }
}

private extension TranslationListView {
    func initUI() {
        size = CGSize(width: xScreenW, height: xScreenH*2/3)
        addRoundedCorners(radius: 20)
        filterButton.addRoundedCorners(radius: 4)
        submitButton.addRoundedCorners(radius: 20)
        filterButton.setTitle(LanguageManager.isLanguageZH ? "筛选": "Фильтры", for: .normal)
        submitButton.setTitle(LanguageManager.isLanguageZH ? "确定": "Подтвердить", for: .normal)
        
        tableView.register(cellType: TranslationListCell.self)
        tableView.register(cellType: GeneralImageCenterTableCell.self)
        tableView.delegate = self
        tableView.dataSource = self
        // .never: 第一个cell挨着屏幕顶, 否则是挨着navbar底部
        tableView.contentInsetAdjustmentBehavior = .never
        // 去掉分割线
        tableView.separatorStyle = .none
        // 修复默认分割线, 向右偏移问题
        // tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        // 分割线颜色
        // tableView.separatorColor = .red
        // iOS 15 默认情况 sectionHeaderTopPadding 会有22个像素的高度，及默认情况，TableView section header 增加22像素的高度
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        
        filterView.isHidden = true
        addSubview(filterView)
        filterView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        filterView.didSelectedItemsBlock = { list in
            self.translationFilterUIModels.removeAll()
            // 深拷贝，复制数据
            var uiModels: [TranslationFilterUIModel] = []
            list.forEach { uiModel in
                var subLis: [TranslationFilterModel] = []
                uiModel.list.forEach { model in
                    subLis.append(model.copy() as! TranslationFilterModel)
                }
                let ui = TranslationFilterUIModel(id: uiModel.id, title: uiModel.title, titleRu: uiModel.titleRu, list: subLis)
                uiModels.append(ui)
            }
            self.translationFilterUIModels = uiModels
            
            list.forEach { uiModel in
                if uiModel.id == 0 {
                    // 语言选择
                    var values: [String] = []
                    uiModel.list.forEach { model in
                        if model.isSelected {
                            values.append(model.id == 0 ? "中": "俄")
                        }
                    }
                    self.requestLang = values.joined(separator: ",")
                    
                } else if uiModel.id == 1 {
                    // 地区选择
                    uiModel.list.forEach { model in
                        if model.name == "地区选择" {
                            self.knowCityId = ""
                            self.knowCityName = ""
                        } else {
                            self.knowCityId = String(model.id)
                            self.knowCityName = model.name
                        }
                    }
                    
                } else if uiModel.id == 2 {
                    // 专业选择
                    var values: [String] = []
                    uiModel.list.forEach { model in
                        if model.isSelected {
                            values.append(String(model.id))
                        }
                    }
                    self.professionalIds = values.joined(separator: ",")
                    
                } else if uiModel.id == 3 {
                    // 价格选择
                    var values: [String] = []
                    uiModel.list.forEach { model in
                        if model.isSelected {
                            values.append(String(model.id))
                        }
                    }
                    self.intentionScore = values.joined(separator: ",")
                    
                } else if uiModel.id == 4 {
                    // 国籍
                    var values: [String] = []
                    uiModel.list.forEach { model in
                        if model.isSelected {
                            values.append(String(model.id))
                        }
                    }
                    self.country = values.joined(separator: ",")
                }
                
            }
            self.page = 1
            self.loadData()
            
        }
        
    }
    
    func initRefresh() {
        tableView.headerRefresh(style: .gif) { [self] in
            page = 1
            loadData()
        }
        tableView.footerRefresh { [self] in
            page += 1
            loadData()
        }
    }
    
    func loadData() {
        let target = JavaAPI.getUserStaff(requestLang: requestLang, professionalIds: professionalIds, country: country, intentionScore: intentionScore, knowCityId: knowCityId, page: page, limit: 20)
        YLRequest.request(target) { [self] result in
            tableView.endRefreshing()
            switch result {
            case .success(let res):
                
                let dataDictionary = res.dataDictionary
                
                let currentPage = dataDictionary["current"] as! Int
                let lastPage = dataDictionary["pages"] as! Int
                
                res.firstPage = currentPage == 1
                res.lastPage = (lastPage == currentPage || lastPage == 0)
                
                let data = dataDictionary["records"]! as! [Any]
                
                let arr = JsonUtil.modelsFromArray(data, TranslatorsModel.self)
                
                if res.firstPage {
                    list.removeAll()
                }
                list.append(contentsOf: arr)
                
                if res.lastPage {
                    tableView.endRefreshingWithNoMoreData()
                }
                tableView.reloadData()
                
            case .failure(let err):
                YLHUD.showHint(.error, err.errMsg)
            }
        }
    }
}

extension TranslationListView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if list.count == 0 {
            return 1
        }
        return list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if list.count == 0 {
            let cell = tableView.dequeueReusableCell(for: indexPath, cellType: GeneralImageCenterTableCell.self)
            cell.coverImageView.image = UIImage(named: "ic_ep_no_data")
            return cell
        }
        let cell = tableView.dequeueReusableCell(for: indexPath, cellType: TranslationListCell.self)
        cell.model = list[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if list.count == 0 {
            return
        }
        list.forEach { m in
            m.isSelected = false
        }
        let model = list[indexPath.row]
        model.isSelected = true
        tableView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if list.count == 0 {
            return frame.size.height - 58 - 72 - xIphoneBottomSafeHeight
        }
        return 86
    }
}
